/*
 * ip_output.c
 *
 *  Created on: 2009-5-5
 *      Author: tian
 */

#include"myip.h"
#include"msgtype.h"
#include<string.h>
#include<errno.h>
#include<stdio.h>

int ip_output(struct iphdr *pheader,char *buf,unsigned int buflen){
	if(buflen+DEFAULT_IP_HEADER_LENGTH/8>BUFLEN){
		fprintf(stderr,"BUFLEN is not enough\n");
		return -1;
	}
	msg ippkg;
	memset(&ippkg,0,sizeof(msg));
	int i=0;
	int j=0;
	int rv;
	char *p=(char*)pheader;/*NULL*/
	pheader->ip_sum=ip_checksum((void*)pheader);

	/*search the route list */
	for(i=MAX_ROUTE_NODE_NUM-1;i>0;i--){
		if(isequal(&(routelst[i].ip_addr),&(pheader->des)))
			break;
	}

	/*create ippkg(message)*/
	ippkg.mtype=MSG_IP_TUNNEL;
	/*copy ip header*/
	//strncpy(ippkg.buf,(char*)pheader,sizeof(struct iphdr));

	for(j=0;j<sizeof(struct iphdr);j++){
		ippkg.buf[j]=p[j];
	}
	ippkg.buflen=sizeof(struct iphdr);
	/*copy data*/
	//strncpy(ippkg.buf+ippkg.buflen,buf,buflen);
	for(j=0;j<buflen;j++){
		ippkg.buf[ippkg.buflen+j]=buf[j];
	}
	ippkg.buflen+=buflen;

	//for test
	printf("send package to ip %s\n",inet_ntoa(pheader->des));
	printf("from ip %s \n",inet_ntoa(pheader->src));
	printf("ip ver:%u ip header len:%u ",pheader->ip_verhl.ip_ver,pheader->ip_verhl.ip_hl*2);
	printf("ip tos:%u ip len:%u\n",pheader->ip_verhl.ip_tos,pheader->ip_verhl.ip_len);
	printf("ip id:%u ip ttl:%u ip pro:%u ip sum:%u\n",pheader->ip_id.ip_id,pheader->ip_ttl,pheader->ip_pro,pheader->ip_sum);
	int ii=0;
	for(;ii<ippkg.buflen;ii++)
		printf("%d ",ippkg.buf[ii]);
	printf("\n");
	//test end

	/*send package*/
	//noblocking, maybe should use block version
	rv=msgsnd(routelst[i].msgqid,&ippkg,sizeof(msg)-sizeof(long),IPC_NOWAIT);
	if(rv==0||errno==EAGAIN)
		return 0;
	else{
		//perror("send ip package error");
		fprintf(stderr,"errno:%d",errno);
		return -1;
	}
}
